import { toRefs } from 'vue';
import { ADD_TODO, REMOVE_TODO, TOGGLE_TODO } from './actionType';
import action from './action';
import initialState from './state';
import { useReducer } from '../../../hooks';

function reducer(state, { type, payload }) {
  //获取action定义的方法
  const { onAddTodo, onToggleTodo, onRemoveTodo } = action(state);

  switch (type) {
    case ADD_TODO:
      onAddTodo(payload);
      break;
    case TOGGLE_TODO:
      onToggleTodo(payload);
      break;
    case REMOVE_TODO:
      onRemoveTodo(payload);
      break;
    default:
      break;
  }
}

//todoReducer
export default function () {
  const [state, todoDispatch] = useReducer(reducer, initialState);

  return {
    //将解构的state属性再次响应式包装
    ...toRefs(state),
    todoDispatch
  };
}
